<template>
  <div class="faceswap-container">
    <!-- 上传和预览区域 -->
    <div v-if="!resultImage" class="upload-section">
      <div class="upload-grid">
        <!-- 左侧：脸部照片上传 -->
        <div class="upload-card">
          <div v-if="!sourceFaceImage" class="upload-area" 
               :class="{ 'drag-over': dragOverSource }" 
               @drop="handleDropSource" 
               @dragover.prevent 
               @dragenter.prevent="dragOverSource = true" 
               @dragleave="dragOverSource = false">
            <div class="upload-icon">
              <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                      d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
              </svg>
            </div>
            <h3 class="upload-title">上传脸部照片</h3>
            <p class="upload-subtitle">提供脸部特征</p>
            <label class="upload-button">
              选择图片
              <input type="file" style="display: none" accept="image/jpeg,image/jpg,image/png,image/webp" 
                     @change="handleSourceSelect" :disabled="processing" />
            </label>
            <p class="upload-hint">支持 JPG、JPEG、PNG、WebP 格式</p>
          </div>
          
          <!-- 脸部照片预览 -->
          <div v-else class="image-preview">
            <img :src="sourceFaceImageUrl" alt="脸部照片" />
            <div class="preview-overlay">
              <button @click="clearSource" class="clear-button">
                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                        d="M6 18L18 6M6 6l12 12"></path>
                </svg>
                重新选择
              </button>
            </div>
            <div class="image-label">脸部照片</div>
          </div>
        </div>

        <!-- 中间箭头指示 -->
        <div class="arrow-indicator">
          <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                  d="M13 7l5 5m0 0l-5 5m5-5H6"></path>
          </svg>
        </div>

        <!-- 右侧：目标照片上传 -->
        <div class="upload-card">
          <div v-if="!targetImage" class="upload-area" 
               :class="{ 'drag-over': dragOverTarget }" 
               @drop="handleDropTarget" 
               @dragover.prevent 
               @dragenter.prevent="dragOverTarget = true" 
               @dragleave="dragOverTarget = false">
            <div class="upload-icon">
              <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                      d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
              </svg>
            </div>
            <h3 class="upload-title">上传目标照片</h3>
            <p class="upload-subtitle">需要被换脸的照片</p>
            <label class="upload-button">
              选择图片
              <input type="file" style="display: none" accept="image/jpeg,image/jpg,image/png,image/webp" 
                     @change="handleTargetSelect" :disabled="processing" />
            </label>
            <p class="upload-hint">支持 JPG、JPEG、PNG、WebP 格式</p>
          </div>
          
          <!-- 目标照片预览 -->
          <div v-else class="image-preview">
            <img :src="targetImageUrl" alt="目标照片" />
            <div class="preview-overlay">
              <button @click="clearTarget" class="clear-button">
                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                        d="M6 18L18 6M6 6l12 12"></path>
                </svg>
                重新选择
              </button>
            </div>
            <div class="image-label">目标照片</div>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <button @click="startFaceSwap" :disabled="!canProcess" class="primary-button">
          <svg v-if="processing" class="loading-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                  d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
          </svg>
          {{ processing ? '处理中...' : '开始换脸' }}
        </button>
        <button @click="resetAll" class="secondary-button" :disabled="processing">
          <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                  d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
          </svg>
          重新开始
        </button>
      </div>
    </div>

    <!-- 结果展示区域 -->
    <div v-else class="result-section">
      <div class="result-header">
        <h3>换脸结果</h3>
        <p>对比查看换脸前后效果</p>
      </div>
      
      <div class="result-comparison">
        <div class="result-item">
          <div class="result-image-wrapper">
            <img :src="targetImageUrl" alt="原始照片" />
          </div>
          <div class="result-label">原始照片</div>
        </div>
        
        <div class="comparison-arrow">
          <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                  d="M13 7l5 5m0 0l-5 5m5-5H6"></path>
          </svg>
        </div>
        
        <div class="result-item">
          <div class="result-image-wrapper highlight">
            <img :src="resultImage" alt="换脸结果" />
            <div class="result-badge">
              <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                      d="M5 13l4 4L19 7"></path>
              </svg>
              完成
            </div>
          </div>
          <div class="result-label highlight">换脸结果</div>
        </div>
      </div>

      <div class="result-actions">
        <button @click="downloadResult" class="download-button">
          <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                  d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
          </svg>
          下载结果
        </button>
        <button @click="resetAll" class="secondary-button">
          <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                  d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
          </svg>
          重新换脸
        </button>
      </div>
    </div>

    <!-- 处理中加载遮罩 -->
    <div v-if="processing" class="loading-overlay">
      <div class="loading-content">
        <div class="loading-spinner"></div>
        <h3>正在处理换脸</h3>
        <p>请稍候，这可能需要几秒钟...</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'

// 状态管理
const sourceFaceImage = ref<File | null>(null)
const targetImage = ref<File | null>(null)
const sourceFaceImageUrl = ref<string>('')
const targetImageUrl = ref<string>('')
const resultImage = ref<string>('')
const processing = ref<boolean>(false)
const dragOverSource = ref<boolean>(false)
const dragOverTarget = ref<boolean>(false)

// 计算属性：是否可以开始处理
const canProcess = computed(() => {
  return sourceFaceImage.value !== null && targetImage.value !== null && !processing.value
})

// 验证文件
const validateFile = (file: File): boolean => {
  // 检查文件类型
  const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp']
  if (!validTypes.includes(file.type)) {
    alert('仅支持 JPG、JPEG、PNG、WebP 格式的图片')
    return false
  }

  // 检查文件大小（10MB）
  const maxSize = 10 * 1024 * 1024
  if (file.size > maxSize) {
    alert('文件大小不能超过 10MB')
    return false
  }

  return true
}

// 读取文件为 Data URL
const readFileAsDataURL = (file: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = (e) => {
      if (e.target?.result) {
        resolve(e.target.result as string)
      } else {
        reject(new Error('读取文件失败'))
      }
    }
    reader.onerror = () => reject(new Error('读取文件失败'))
    reader.readAsDataURL(file)
  })
}

// 处理脸部照片上传
const handleSourceSelect = async (e: Event) => {
  const input = e.target as HTMLInputElement
  if (input.files && input.files[0]) {
    await handleSourceFile(input.files[0])
  }
}

const handleDropSource = async (e: DragEvent) => {
  e.preventDefault()
  dragOverSource.value = false
  
  if (e.dataTransfer?.files && e.dataTransfer.files[0]) {
    await handleSourceFile(e.dataTransfer.files[0])
  }
}

const handleSourceFile = async (file: File) => {
  if (!validateFile(file)) return
  
  sourceFaceImage.value = file
  sourceFaceImageUrl.value = await readFileAsDataURL(file)
}

// 处理目标照片上传
const handleTargetSelect = async (e: Event) => {
  const input = e.target as HTMLInputElement
  if (input.files && input.files[0]) {
    await handleTargetFile(input.files[0])
  }
}

const handleDropTarget = async (e: DragEvent) => {
  e.preventDefault()
  dragOverTarget.value = false
  
  if (e.dataTransfer?.files && e.dataTransfer.files[0]) {
    await handleTargetFile(e.dataTransfer.files[0])
  }
}

const handleTargetFile = async (file: File) => {
  if (!validateFile(file)) return
  
  targetImage.value = file
  targetImageUrl.value = await readFileAsDataURL(file)
}

// 清除脸部照片
const clearSource = () => {
  sourceFaceImage.value = null
  sourceFaceImageUrl.value = ''
}

// 清除目标照片
const clearTarget = () => {
  targetImage.value = null
  targetImageUrl.value = ''
}

// 开始换脸（模拟处理）
const startFaceSwap = async () => {
  if (!canProcess.value) return
  
  processing.value = true
  
  // 模拟API调用延迟（3秒）
  await new Promise(resolve => setTimeout(resolve, 3000))
  
  // 暂时使用目标图片作为结果（后续集成真实API）
  resultImage.value = targetImageUrl.value
  
  processing.value = false
}

// 下载结果
const downloadResult = () => {
  if (!resultImage.value) return
  
  const link = document.createElement('a')
  link.href = resultImage.value
  link.download = `faceswap-result-${Date.now()}.jpg`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 重置所有状态
const resetAll = () => {
  sourceFaceImage.value = null
  targetImage.value = null
  sourceFaceImageUrl.value = ''
  targetImageUrl.value = ''
  resultImage.value = ''
  processing.value = false
  dragOverSource.value = false
  dragOverTarget.value = false
}
</script>

<style scoped>
.faceswap-container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
}

/* 上传区域 */
.upload-section {
  padding: 2rem 0;
}

.upload-grid {
  display: grid;
  grid-template-columns: 1fr auto 1fr;
  gap: 2rem;
  align-items: center;
  margin-bottom: 2rem;
}

@media (max-width: 768px) {
  .upload-grid {
    grid-template-columns: 1fr;
    gap: 1.5rem;
  }
  
  .arrow-indicator {
    transform: rotate(90deg);
  }
}

.upload-card {
  position: relative;
}

.upload-area {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border: 2px dashed #d1d5db;
  border-radius: 16px;
  padding: 2rem;
  text-align: center;
  transition: all 0.3s ease;
  min-height: 320px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.upload-area:hover {
  border-color: #60a5fa;
  background: rgba(96, 165, 250, 0.05);
  transform: translateY(-2px);
}

.upload-area.drag-over {
  border-color: #3b82f6;
  background: rgba(59, 130, 246, 0.1);
  transform: scale(1.02);
}

.upload-icon {
  width: 80px;
  height: 80px;
  margin: 0 auto 1.5rem;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.upload-icon svg {
  width: 40px;
  height: 40px;
  color: white;
}

.upload-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 0.5rem;
}

.upload-subtitle {
  font-size: 0.95rem;
  color: #6b7280;
  margin-bottom: 1.5rem;
}

.upload-button {
  display: inline-block;
  padding: 12px 32px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.upload-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.5);
}

.upload-hint {
  font-size: 0.85rem;
  color: #9ca3af;
  margin-top: 1rem;
}

/* 箭头指示器 */
.arrow-indicator {
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.arrow-indicator svg {
  width: 24px;
  height: 24px;
  color: white;
}

/* 图片预览 */
.image-preview {
  position: relative;
  border-radius: 16px;
  overflow: hidden;
  background: #f3f4f6;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.image-preview img {
  width: 100%;
  height: auto;
  min-height: 320px;
  object-fit: cover;
  display: block;
}

.preview-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.image-preview:hover .preview-overlay {
  opacity: 1;
}

.clear-button {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 10px 20px;
  background: white;
  color: #1f2937;
  border: none;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.clear-button:hover {
  background: #f3f4f6;
  transform: scale(1.05);
}

.clear-button svg {
  width: 18px;
  height: 18px;
}

.image-label {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 1rem;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.7), transparent);
  color: white;
  font-weight: 600;
  text-align: center;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  justify-content: center;
  gap: 1rem;
  margin-top: 2rem;
}

@media (max-width: 768px) {
  .action-buttons {
    flex-direction: column;
  }
}

.primary-button {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  padding: 14px 40px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.primary-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.5);
}

.primary-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  pointer-events: none;
}

.loading-icon {
  width: 20px;
  height: 20px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.secondary-button {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  padding: 14px 32px;
  background: rgba(255, 255, 255, 0.95);
  color: #6b7280;
  border: 2px solid #e5e7eb;
  border-radius: 12px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.secondary-button:hover:not(:disabled) {
  background: white;
  border-color: #d1d5db;
  color: #374151;
  transform: translateY(-2px);
}

.secondary-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.secondary-button svg {
  width: 18px;
  height: 18px;
}

/* 结果展示 */
.result-section {
  padding: 2rem 0;
}

.result-header {
  text-align: center;
  margin-bottom: 2rem;
}

.result-header h3 {
  font-size: 1.75rem;
  font-weight: 700;
  color: #1f2937;
  margin-bottom: 0.5rem;
}

.result-header p {
  font-size: 1rem;
  color: #6b7280;
}

.result-comparison {
  display: grid;
  grid-template-columns: 1fr auto 1fr;
  gap: 2rem;
  align-items: center;
  margin-bottom: 2rem;
}

@media (max-width: 768px) {
  .result-comparison {
    grid-template-columns: 1fr;
    gap: 1.5rem;
  }
  
  .comparison-arrow {
    transform: rotate(90deg);
  }
}

.result-item {
  text-align: center;
}

.result-image-wrapper {
  position: relative;
  border-radius: 16px;
  overflow: hidden;
  background: #f3f4f6;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.result-image-wrapper.highlight {
  box-shadow: 0 8px 30px rgba(102, 126, 234, 0.4);
  border: 3px solid #667eea;
}

.result-image-wrapper img {
  width: 100%;
  height: auto;
  display: block;
}

.result-badge {
  position: absolute;
  top: 1rem;
  right: 1rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 8px 16px;
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  color: white;
  border-radius: 8px;
  font-weight: 600;
  font-size: 0.9rem;
  box-shadow: 0 4px 15px rgba(16, 185, 129, 0.4);
}

.result-badge svg {
  width: 18px;
  height: 18px;
}

.result-label {
  margin-top: 1rem;
  font-size: 1rem;
  font-weight: 600;
  color: #6b7280;
}

.result-label.highlight {
  color: #667eea;
  font-size: 1.1rem;
}

.comparison-arrow {
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.comparison-arrow svg {
  width: 24px;
  height: 24px;
  color: white;
}

.result-actions {
  display: flex;
  justify-content: center;
  gap: 1rem;
  margin-top: 2rem;
}

@media (max-width: 768px) {
  .result-actions {
    flex-direction: column;
  }
}

.download-button {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  padding: 14px 40px;
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(16, 185, 129, 0.4);
}

.download-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(16, 185, 129, 0.5);
}

.download-button svg {
  width: 20px;
  height: 20px;
}

/* 加载遮罩 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  backdrop-filter: blur(10px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.loading-content {
  text-align: center;
  color: white;
}

.loading-spinner {
  width: 60px;
  height: 60px;
  margin: 0 auto 1.5rem;
  border: 4px solid rgba(255, 255, 255, 0.3);
  border-top-color: white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.loading-content h3 {
  font-size: 1.5rem;
  font-weight: 600;
  margin-bottom: 0.5rem;
}

.loading-content p {
  font-size: 1rem;
  opacity: 0.8;
}
</style>

